# -*-coding: utf-8 -*-
"""
    @Theme   : MongoDB CRUD 操作
    @Time    : 2024/6/9 10:43
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
import os
from pymongo import MongoClient

DATABASE_URI = os.getenv('MONGODB_URI')


class DataBaseManager(object):
    def __init__(self, database, collection):
        client = MongoClient(DATABASE_URI) if DATABASE_URI else MongoClient()
        database = client.get_database(database)
        self.collection = database.get_collection(collection)

    def query_info(self):
        info_list = list(self.collection.find({'deleted': 0}, {'_id': 0}))
        return info_list

    def _query_last_id(self):
        last_info = self.collection.find_one({}, {'_id': 0, 'id': 1}, sort=[('_id', -1)])
        return last_info['id'] if last_info else 0

    def add_info(self, param_dict):
        param_dict['id'] = self._query_last_id() + 1
        try:
            self.collection.insert_one(param_dict)
        except Exception as e:
            print('插入数据异常：', e)
            return False
        return True

    def update_info(self, people_id, param_dict):
        try:
            y = self.collection.update_one({'id': people_id}, {'$set': param_dict})
            print(y)
        except Exception as e:
            print('更新数据错误：', e)
            return False
        return True

    def del_info(self, people_id):
        return self.update_info(people_id, {'deleted': 1})
